<template>
  <div class="common-list-container__v2" v-loading.fullscreen.lock="loading || typesLoading">
    <div class="common-list-section__v2 search-box">
      <div class="wait-accept-box">
        <h3>{{countInfo.taskPoolTotal}}</h3>
        <p>待接受工单</p>
        <i class="iconfont icon-list"></i>
      </div>
      <el-tooltip effect="dark" content="工单池超时设置请在系统管理-工单设置中配置" placement="bottom">
        <div class="overtime-task-box ml_12">
          <h3>{{countInfo.overTimeCount}}</h3>
          <p>超时工单</p>
          <i class="iconfont icon-list"></i>
        </div>
      </el-tooltip>
    </div>
    <!--s 头部搜索栏 -->
    <div class="common-list-header__v2">
      <div>
        <el-input class="search-input" placeholder="请输入工单编号/客户信息" v-model="searchParams.keyword">
          <el-button class="search-input__append" slot="append" @click="search">搜索</el-button>
        </el-input>
        <el-button type="plain-third" class="ml_12" @click="resetParams">重置</el-button>
      </div>
      <span class="advanced-search-btn pointer" @click.self="panelSearchAdvancedToggle">
        <i class="iconfont icon-filter" @click.self="panelSearchAdvancedToggle"></i>
        高级搜索
      </span>
    </div>
    <!--e 头部搜索栏 -->
    <!--s 内容 -->
    <div class="common-list-view__v2 mt_12">
      <div class="common-list-view-header__v2">
        <div>
          <el-button @click="batchDelete">删 除</el-button>
          <el-button type="primary" @click="batchReallotDialogOpen">批量转派</el-button>
          <el-tooltip effect="dark" content="当前视图有新工单时，请通知我" placement="top">
            <i
              class="iconfont icon-dingyuetongzhiguanli ml_20 pointer"
              :class="hasSub && 'actived'"
              @click="toggleTaskSubscribe">
              {{ hasSub ? '已订阅': '未订阅'}}
            </i>
          </el-tooltip>
        </div>
        <div>
          <el-dropdown>
            <div class="task-ai task-flex task-font14 task-c6 task-pointer cur-point">
              <span class="task-mr4 task-ml4">{{
                mapShow ? "地图模式" : "列表模式"
              }}</span>
              <i class="iconfont icon-fdn-select task-icon"></i>
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <div @click="taskMode('列表模式')">列表模式</div>
              </el-dropdown-item>
              <el-dropdown-item>
                <div @click="taskMode('地图模式')">地图模式</div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <span class="el-dropdown-link cur-point mar-l-12" @click="showAdvancedSetting">
            选择列
            <i class="iconfont icon-fdn-select"></i>
          </span>
        </div>
      </div>
      <!-- 已勾选项 -->
      <div
        class="common-list-selection__v2 mt_8"
      >
        <base-selection-bar
          ref="baseSelectionBar"
          v-model="multipleSelection"
          @toggle-selection="toggleSelection"
          @show-panel="showSelectionPanel"
        />
        <base-selection-panel
          ref="selectionPanel"
          :columns="[{label: '工单编号',prop: 'taskNo'},{label: '工单类型',prop: 'templateName'}]"
          :data="multipleSelection"
          :table-ref="$refs.multipleTable"
          @toggleSelection="toggleSelection"
          @change="(data) => multipleSelection = data">
        </base-selection-panel>
      </div>
      <!--s 表格 -->
      <el-table
        ref="multipleTable"
        class="common-list-table__v2 mt_8"
        stripe
        :data="taskPage.list"
        :highlight-current-row="false"
        :border="true"
        @select="handleSelection"
        @select-all="handleSelection"
        @sort-change="sortChange"
        header-row-class-name="common-list-table-header__v2"
      >
        <el-table-column
          type="selection"
          width="48"
          align="center"
          class-name="select-column"
        ></el-table-column>
        <el-table-column
          v-for="column in columns"
          v-if="column && column.show"
          show-overflow-tooltip
          :align="column.align"
          :key="column.field"
          :label="column.displayName"
          :min-width="column.minWidth"
          :prop="column.field"
          :sortable="column.sortable"
          :width="column.width"
          :resizable="true"
        >
          <template slot-scope="scope">
            <template v-if="column.renderCell">
              <base-table-cell :render-cell="column.renderCell" :column="column" :row="scope.row"></base-table-cell>
            </template>
            <template v-else>
              {{ $formatFormField(column, scope.row) }}
            </template>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作">
          <template slot-scope="scope">
            <el-button 
              :disabled="scope.row.inApprove == 1"
              type="text"
              @click="accpetTask(scope.row)">
              接 单
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--e 表格 -->
      <!--s 分页信息 -->
      <div class="common-list-table-footer__v2 mt_12">
        <el-pagination
          background
          hide-on-single-page
          :page-sizes="defaultTableData.defaultPageSizes"
          @current-change="jump"
          @size-change="handleSizeChange"
          :page-size="searchParams.pageSize"
          :current-page="searchParams.page"
          :layout="defaultTableData.defaultLayout"
          :total="taskPage.totalElements"
        >
        </el-pagination>
      </div>
      <!--e 分页信息 -->
    </div>
    <!--e 内容 -->

    <!-- 高级搜索框 -->
    <base-search-drawer
      :show.sync="visible"
      @reset="resetParams"
      @search="search"
      @changeWidth="setAdvanceSearchColumn"
    >
      <base-search-panel ref="searchPanel" :column-num="columnNum" :fields="advanceSearchColumn"/>
    </base-search-drawer>
    <!-- 选择列 --> 
    <biz-select-column ref="advanced" @save="saveColumnStatus" />
    <!--  计划时间弹窗(接单) -->
    <plantime-dialog ref="planTimeDialog" :task="task" :field="planTimeField" :modifiable="taskConfig.taskPlanTime" />
    <!-- 批量转派 -->
    <task-transfer ref="TaskTransfer" :task-id-list="selectedIds" :task-config="taskConfig"/>
    <!-- 地图派单 -->
    <task-map
      :map-show="mapShow"
      @hide="mapShow = false"
      :task-config="taskConfig"
      :task-types-map="taskTypesMap"
      :config="{ selectedIds, searchParams: {...advancedSearchParams, keyword: searchParams.keyword,} }"
    />
  </div>
</template>

<script>
// api
import * as TaskApi from '@src/api/TaskApi';
// model
import Page from '@model/Page';
import {getColumnFields, getAdvancedFields} from './fields';
import { defaultTableData } from '@src/util/table'
import TaskConfig from '@model/config/TaskConfig.ts'
// components
import BaseSearchDrawer from 'packages/BaseSearchDrawer';
import BaseSearchPanel from 'packages/BaseSearchPanel';
import BaseTableCell from 'packages/BaseTableCell';
import TaskMap from './componets/TaskMap';
import PlanTimeDialog from '../../view/components/PlanTimeDialog.vue';
import TaskTransfer from './componets/TaskTransfer';

import formatColumn from 'packages/BaseTableCell/formatColumn';

const MAXCHECK = 500;

export default {
  name: 'task-pool-list',
  data() {
    return {
      defaultTableData,
      hasSub: false,
      countInfo: {
        taskPoolTotal: '--',
        overTimeCount: '--'
      },

      currentTaskType: {},
      taskTypes: [],
      taskTypesMap: {},
      taskFields: [],
      multipleSelection: [],

      taskConfig: {},
      planTimeField: {},
      task: {},

      searchParams: {
        keyword: '',
        pageSize: 10,
        page: 1,
        sorts: []
      },
      advancedSearchParams: {},
      taskPage: new Page(),

      mapShow: false,
      visible: false,
      columns: getColumnFields(this),
      columnNum: 1,

      loading: false,
      typesLoading: false
    }
  },
  computed: {
    /** 高级搜索字段 */
    advanceSearchColumn() {
      return [
        ...getAdvancedFields(this),
        ...this.taskFields.filter(filed => { // 过滤重复项
          return !getColumnFields(this).some(item => item.field === filed.fieldName);
        })
      ].filter(item => 
        item.isSearch && item.isSearch == 1
      );
    },
    /** 已选择工单ids */
    selectedIds() {
      return this.multipleSelection.map(item => item.id);
    },
    // /** 获取是否开启联系人地址产品 */
    // customerSetting() {
    //   let {
    //     address,
    //     product,
    //     linkman,
    //   } = this.currentTaskTypeCustomerFieldSetting;
    //   return {
    //     addressOn: address == true,
    //     productOn: product == true,
    //     linkmanOn: linkman == true,
    //   };
    // },
    // /** 当前工单类型客户字段设置 */
    // currentTaskTypeCustomerFieldSetting() {
    //   let customerFields = this.taskFields.filter(
    //     (field) => field.formType == 'customer'
    //   );
    //   let customerField = customerFields[0];
    //   let customerSetting = {};

    //   if (customerField) {
    //     let setting = customerField.setting || {};
    //     customerSetting = setting.customerOption || {};
    //   }

    //   return customerSetting;
    // },
    // /** 服务项目 服务内容 优先级 描述系统字段设置 */
    // sysFieldsSetting() {
    //   let serviceContentFields = this.taskFields.filter(
    //     (field) => field.formType == 'serviceContent'
    //   );
    //   let serviceTypeFields = this.taskFields.filter(
    //     (field) => field.formType == 'serviceType'
    //   );
    //   let levelFields = this.taskFields.filter(
    //     (field) => field.formType == 'level'
    //   );
    //   let descriptionFields = this.taskFields.filter(
    //     (field) => field.formType == 'description'
    //   );

    //   let serviceContentField = serviceContentFields[0] || {};
    //   let serviceTypeField = serviceTypeFields[0] || {};
    //   let levelField = levelFields[0] || {};
    //   let descriptionField = descriptionFields[0] || {};

    //   let hasServiceContent = serviceContentField.enabled == 1;
    //   let hasServiceType = serviceTypeField.enabled == 1;
    //   let hasLevel = levelField.enabled == 1;
    //   let hasDescription = descriptionField.enabled == 1;

    //   return {
    //     hasServiceContent,
    //     hasServiceType,
    //     hasLevel,
    //     hasDescription
    //   };
    // },
    taskTypeList() {
      return [
        {
          name: '全部', id: ''
        },
        ...this.taskTypes
      ]
    },
    serviceTypeDataSource() {
      let field = this.taskFields.find(f => {
        if(f.fieldName === 'serviceType') return true;
        return false;
      }) || {};
      
      let dataSource = field?.setting?.dataSource || [];
      return [{text: '全部', value: ''}, ...dataSource];
    },
    serviceContentDataSource() {
      let field = this.taskFields.find(f => {
        if(f.fieldName === 'serviceContent') return true;
        return false;
      }) || {};
      
      let dataSource = field?.setting?.dataSource || [];
      return [{text: '全部', value: ''}, ...dataSource];
    },
    levelDataSource() {
      let field = this.taskFields.find(f => {
        if(f.fieldName === 'level') return true;
        return false;
      }) || {};
      
      let dataSource = field?.setting?.dataSource || [];
      return [{text: '全部', value: ''}, ...dataSource];
    }
  },
  watch: {
    taskFields() {
      this.columns = [
        ...getColumnFields(this),
        ...this.taskFields.filter(f => {
          return f.isSystem !== 1 
          && !['attachment', 'separator', 'info', 'autograph'].includes(f.formType)
        })
      ].map(field => {
        return {
          ...formatColumn(field),
          field: field.field || field.fieldName
        }
      });
    },
    'currentTaskType.id': {
      handler(newVal, oldVal) {
        if(newVal && newVal != oldVal) {
          this.fetchTaskFields();
        }
      }
    }
  },
  methods: {
    /**
     * @description 选择展示模式
     */
    taskMode(type) {
      this.mapShow = type === '地图模式';
    },
    /** 打开已选panel */
    showSelectionPanel() {
      this.$refs.selectionPanel.openPanel();
    },
    /** 打开高级搜索 */
    panelSearchAdvancedToggle() {
      window.TDAPP.onEvent('pc：工单池列表-高级搜索事件');
      this.visible = true;
    },
    /** 关闭高级搜索弹框 */
    closeDrawer(){
      this.visible = false;
    },
    resetParams () {
      const fromId = window.frameElement.getAttribute('id');
      this.$platform.refreshTab(fromId);
    },
    /**  获取工单类型（全部） */
    fetchTaskTypesMap() {
      this.typesLoading = true;
      TaskApi.getTaskTypesMap().then((data) => {
        this.typesLoading = false;
        let isSuccess = data.success
        if (!isSuccess) return
      
        let taskTypes = data?.result || []
        // key : 工单类型id(string) -> value: TaskType
        this.taskTypesMap = taskTypes
          .reduce((acc, currentTaskType) => {
            acc[currentTaskType.templateId] = currentTaskType
            return acc
          }, {})
      }).catch(err => {
        this.typesLoading = false;
        console.error(err)
      })
    },
    /**
     * @description 获取工单字段列表
     * @return {Promise}
     */
    fetchTaskFields() {
      let params = {
        typeId: this.currentTaskType.id || '',
        tableName: 'task',
        isFromSetting: false
      };
      TaskApi.getAllFields(params).then((result) => {
        result.forEach((field) => {
          field.group = 'task';
          field.label = field.displayName;
          field.field = field.fieldName;
          field.show = true;
        });
        this.taskFields = result;
      }).catch(err => {
        console.error(err);
      });
    },
    fetchPoolCount() {
      TaskApi.getTaskPoolHeadInfos()
        .then(res => {
          this.countInfo = {
            taskPoolTotal: res.taskPoolTotal,
            overTimeCount: res.overTimeCount
          }
        }).catch(err => {
          console.error(err);
        })
    },
    fetchInitData() {
      TaskApi.getPoolListInit()
        .then(res=> {
          let {taskTypeList = [], hasSub, taskConfig = new TaskConfig()} = res;
          this.hasSub = hasSub;
          this.taskTypes = taskTypeList;
          this.taskConfig = taskConfig;
        })
        .catch(err => console.error(err));
    },
    /** 获取列表数据 */
    fetchPoolList(searchParams) {
      let params = {
        ...this.searchParams,
        ...searchParams
      }

      console.log('搜索参数: ', params);

      this.loading = true;
      TaskApi.getPoolList(params)
        .then((res) => {
          this.loading = false;
          if(!res.success) {
            return this.$platform.alert(res.message);
          }

          this.taskPage = res.result || {};
          this.taskPage.list = res.result.content;

          // 把选中的匹配出来
          if (this.multipleSelection.length) {
            this.$nextTick(() => {
              this.multipleSelection.forEach(item => {
                this.taskPage.list.forEach(v => {
                  if (v.id === item.id) {
                    this.$refs.multipleTable.toggleRowSelection(v);
                  }
                })
              })
            })
          }
        })
        .catch(err => {
          this.loading = false;
          console.error(err);
        })
    },
    /** 搜索事件 */
    search () {
      // 获取高级搜索参数
      let advancedSearchParams = this.$refs.searchPanel ? this.$refs.searchPanel.buildParams() : {};
      if(advancedSearchParams.taskType) {
        let typeId = advancedSearchParams.taskType;
        let taskType = this.taskTypes.find(item => item.id === typeId);
        this.currentTaskType = {
          id: typeId,
          name: taskType && taskType.name
        };
        advancedSearchParams.templateId = typeId;
      }

      let {customer, tlmName, area = {}, product, createUser = [] } = advancedSearchParams;
      advancedSearchParams = {
        ...advancedSearchParams,
        customerId: customer || '',
        customerLinkman: tlmName || '',
        cusProvince: area.province || '',
        cusDist: area.dist || '',
        cusCity: area.city || '',
        cusAddress: area.address || '',
        productId: product,
        createUserIds: createUser
      }
      this.advancedSearchParams = advancedSearchParams;

      this.fetchPoolList(advancedSearchParams);
      this.closeDrawer();
    },
    /** 打开选择列 */
    showAdvancedSetting(){
      window.TDAPP.onEvent('pc：工单池列表-选择列事件');
      this.$refs.advanced.open(this.columns, this.currentTaskType);
    },
    /** 选择列更新事件 */
    saveColumnStatus(event) {
      let columns = event.data || []

      this.columns = []
      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice());
        this.$message.success(this.$t('common.base.saveSuccess'));
      })
    },
    /** 设置高级搜索展示列数 */
    setAdvanceSearchColumn(command) {
      this.columnNum = Number(command);
    },
    /** 表格选择操作 */
    handleSelection(selection) {
      let selected = [];

      selected = [
        ...this.multipleSelection.filter(s => {
          return !(this.taskPage.list.some(t => t.id === s.id));
        }),
        ...selection
      ];

      if(selected.length > MAXCHECK) {
        return this.$platform.alert(`最多只能选择${MAXCHECK}条数据`);
      }
      
      this.multipleSelection = selected;
    },
    /** 排序变化  */
    sortChange(option) {
      let {column, order, prop} = option;
      if(prop === 'customer') {
        prop = 'customerName';
      }

      if(column === null) {
        this.searchParams.sorts = [];
      }else{
        this.searchParams.sorts = [{
          property: prop.indexOf('field_') > -1 ? `attribute.${prop}` : prop,
          direction: order === 'ascending' ? 'ASC' : 'DESC',
        }]
      }
      
      this.search();
    },
    /** 清空选择框 */
    toggleSelection() {
      this.multipleSelection = [];
      this.$refs.multipleTable.clearSelection();
    },
    /** 页码跳转 */
    jump(page) {
      this.searchParams.page = page;
      this.taskPage.list = [];
      this.search();
    },
    /** 页大小改变 */
    handleSizeChange(pageSize) {
      this.searchParams.pageSize = pageSize;
      this.searchParams.page = 1;

      this.search();
    },
    /** 取消或订阅工单 */
    async toggleTaskSubscribe() {
      let action = this.hasSub ? TaskApi.taskUnSubscribe : TaskApi.taskSubscribe;
      let tip = this.hasSub ? '已取消订阅通知' : '已订阅通知';
      try {
        let res = await action({module:'taskPool'});
        if(res.status == 0){
          this.$platform.alert(tip);
          this.hasSub = !this.hasSub;
        }else {
          this.$platform.alert(res.message);
        }
      } catch (error) {
        console.error(error);
      }
    },
    /** 接受工单操作 */
    async accpetTask(row) {
      let taskType = this.taskTypesMap[row.templateId];
      for (const key in taskType.field) {
        if(taskType.field[key].name === 'planTime') {
          this.planTimeField = taskType.field[key];
        }
      }
      this.task = row;

      this.$nextTick(() => {
        this.$refs.planTimeDialog.openDialog('acceptFromPool');
      })
    },
    /** 批量删除 */
    async batchDelete() {
      const {
        selectedIds,
        $platform
      } = this;
      // let params = selectedIds
      //   .map((item) => {
      //     return `taskIds=${item}`;
      //   })
      //   .join('&');
      if (!selectedIds.length) {
        $platform.alert('请选择需要删除的数据');
        return;
      }
      window.TDAPP.onEvent('pc：工单列表-删除工单');
      try {
        const {
          succ,
          status,
          message,
          data
        } = await TaskApi.withPart(selectedIds);
        if (succ) {
          let warningMsg = '确定要删除所选工单吗？';
          if (status) {
            warningMsg = `${message}，确定要删除所选工单吗？`;
          } else if (!data.status && data.length > 0) {
            warningMsg = '以下工单已添加备件: 工单编号';
            if (data.length <= 5) {
              warningMsg += data.join('、');
            } else {
              let ids = [];
              for (let i = 0; i < 5; i++) {
                ids.push(data[i]);
              }
              warningMsg += `${ids.join('、')}等${data.length}个`;
            }
            warningMsg += '，确定要删除么？';
          }
          let confirm = await this.$platform.confirm(warningMsg);
          if (confirm) {
            // 删除工单
            const {
              success, message
            } = await TaskApi.deleteTask(selectedIds);
            if (success) {
              $platform.alert('删除成功');
              this.multipleSelection = [];
              this.jump(1);
            } else{
              this.$platform.alert(message);
            }
          }
        }
      } catch (error) {
        console.error(error);
      }
    },
    /** 批量转派 */
    batchReallotDialogOpen() {
      if(this.multipleSelection.length < 1) {
        return this.$platform.alert('请选择需要批量转派的工单');
      }

      this.$refs.TaskTransfer.openSendMessageDialog();
    }
  },
  mounted() {
    this.fetchPoolCount();
    this.fetchInitData();
    this.fetchTaskFields();
    this.fetchPoolList();
    this.fetchTaskTypesMap();
  },
  components: {
    [BaseSearchDrawer.name]: BaseSearchDrawer,
    [BaseSearchPanel.name]: BaseSearchPanel,
    [BaseTableCell.name]: BaseTableCell,
    [TaskMap.name]: TaskMap,
    [PlanTimeDialog.name]: PlanTimeDialog,
    [TaskTransfer.name]: TaskTransfer
  }
}
</script>

<style lang="scss" scoped>
.search-input{
  width: 440px;
}

.search-input__append{
  @include backgroundColorImportant();
  color: #fff !important;
  border-radius: 0 4px 4px 0 !important;
}

.advanced-search-btn{
  @include fontColor;
}

.search-box{
  display: flex;
  margin-bottom: 12px;
  & > div{
    cursor: pointer;
    position: relative;
    width: 220px;
    height: 85px;
    padding: 12px;
    color: #fff;
    h3{
      font-size: 22px;
    }
    p{
      font-size: 15px;
      margin-bottom: 0;
    }
    .icon-list{
      position: absolute;
      top: 50%;
      right: 12px;
      transform: translateY(-60%);
      font-size: 50px;
      opacity: .3;
      transition: transform .2s ease;
    }
    &.wait-accept-box{
      background-color: #33b0ff;
      &:hover{
        .icon-list{
          transform: translateY(-45%);
        }
      }
    } 
    &.overtime-task-box{
      background-color: #f9b854;
      &:hover{
        .icon-list{
          transform: translateY(-45%);
        }
      }
    }
  }
}

.icon-dingyuetongzhiguanli{
  font-size: 14px;
  &.actived{
    color: #69b5f0;
  }
}

.el-input-group__append{
  border-radius: 0 4px 4px 0;
}

::v-deep .task-plantime-dialog{
  .base-modal-body{
    padding: 20px;
  }
}
</style>